package cn.calm.swing.osgi.host.tracker;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.swing.JMenuBar;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

import cn.calm.swing.osgi.api.DefaultServiceTracker;
import cn.calm.swing.osgi.api.MenuService;
import cn.calm.swing.osgi.host.ui.MainFrame;

public class MenuServiceTracker extends
		DefaultServiceTracker<MenuService, MenuService> {
	protected final static int ADDED = 1, REMOVED = 2, MODIFIED = 3;
	private MainFrame frame;

	public MenuServiceTracker(BundleContext context, MainFrame frame) {
		super(context, MenuService.class, null);
		this.frame = frame;
	}

	protected void processShape(final int action,
			ServiceReference<MenuService> reference, final MenuService service) {
		switch (action) {
		case MODIFIED:
			if (service.getParent() == null) {
				JMenuBar menuBar = frame.getJMenuBar();
				menuBar.remove(service.getMenu());
			} else {
				service.getParent().getMenu().remove(service.getMenu());
			}
		case ADDED:
//			if (service.getParent() == null) {
//				JMenuBar menuBar = frame.getJMenuBar();
//				menuBar.removeAll();
//			}
			processAdd(reference, service, MenuService.MENU_TREE,
					MenuService.class);
			break;
		case REMOVED:
			if (service.getParent() == null) {
				JMenuBar menuBar = frame.getJMenuBar();
				menuBar.remove(service.getMenu());
				menuBar.updateUI();
			} else {
				service.getParent().getMenu().remove(service.getMenu());
				service.getParent().getMenu().updateUI();
			}
		default:
			break;
		}
	}

	protected void prepreParent(MenuService parent) {
		parent.getMenu().removeAll();
	}

	protected void sortService(List<ServiceReference<MenuService>> list) {
		Collections.sort(list, new Comparator<ServiceReference<MenuService>>() {

			@Override
			public int compare(ServiceReference<MenuService> o1,
					ServiceReference<MenuService> o2) {
				MenuService ser1 = context.getService(o1);
				MenuService ser2 = context.getService(o2);
				if (ser1.getIndex() == ser2.getIndex()) {
					return ser1.getMenu().getText()
							.compareTo(ser2.getMenu().getText());
				} else {
					return ser1.getIndex() - ser2.getIndex();
				}
			}
		});
	}

	protected void processParent(MenuService service, MenuService parent) {
		if (parent == null) {
			JMenuBar menuBar = frame.getJMenuBar();
			menuBar.add(service.getMenu());
			menuBar.updateUI();
		} else {
			service.setParent(parent);
			parent.getMenu().add(service.getMenu());
		}
	}
}
